﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Rocket : MonoBehaviour {

    public bool isLife = true;
    public bool impulse = true;
    public float impulseSize = 5;
    public float impulsePower = 1;

    bool wasDestroyed = false;
    bool wasImpulsed = false;

    HashSet<int> ids = new HashSet<int>();

    void Update()
    {
        if (impulse && rigidbody2D.isKinematic && !wasImpulsed)
        {
            wasImpulsed = true;
            Impulse();
        }
        if (!isLife && !wasDestroyed)
        {
            wasDestroyed = true;
            GameObject.DestroyImmediate(gameObject);
        }
    }

    void Impulse()
    {
        CircleCollider2D impulseCollider = gameObject.AddComponent<CircleCollider2D>();
        impulseCollider.radius = impulseSize;
        impulseCollider.isTrigger = true;
    }

    void OnTriggerStay2D(Collider2D other)
    {
        if (other.attachedRigidbody != null && !other.tag.Equals("Ignore boom"))
        {
            if (!ids.Contains(other.gameObject.GetInstanceID()))
            {
                Vector2 distance = other.transform.position - transform.position;
                float power = impulsePower / other.rigidbody2D.mass * (impulseSize - distance.sqrMagnitude) / impulseSize;
                Vector2 force = distance.normalized * power;
                other.attachedRigidbody.velocity += force;
            }     

            ids.Add(other.gameObject.GetInstanceID());
        }
    }
}
